<template>
    <div class='type'>
        <el-tag :key="tag.id" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag.id)">
            {{ tag.typename }}
        </el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
            @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
    </div>
</template>

<script>
export default {
    name: 'type-page',
    data() {
        return {
            dynamicTags: [],
            inputVisible: false,
            inputValue: '',
            loading:false,
            url: {
                list: '/article/type',
                add: '/article/type/add',
                delete: '/article/type/delete'
            }
        }
    },
    created() {
        this.getTypeList()
    },
    methods: {
        getTypeList() {
            this.$http.get(this.url.list).then(res => {
                console.log(res);
                if (res.status == 200) {
                    this.dynamicTags = res.data.results
                }
            })
        },
        handleClose(id) {
            this.$http.post(this.url.delete+'/'+id).then(res => {
                console.log(res);
                if (res.status == 200) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getTypeList()
                }
            })
        },
        showInput() {
            console.log(1);
            this.inputVisible = true;
            this.$nextTick(() => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm() {
            if(this.loading){
                return 
            }   
            console.log(2);
            let inputValue = this.inputValue.trim();
            if (inputValue) {
                this.loading = true
                this.$http.post(this.url.add, {
                    typename: inputValue
                }).then(res => {
                    console.log(res);
                    if (res.status == 200) {
                        this.$message({
                            message: '添加成功',
                            type: 'success'
                        });
                        this.loading = false
                        this.getTypeList()
                    }
                })
            }
            this.inputVisible = false;
            this.inputValue = '';
        }
    }
}
</script>

<style scoped lang='less'>
.el-tag+.el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>